package assess

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math/big"
	"net/http"
	"sort"
	"strconv"
	"strings"
	"time"

	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/assess"
	"gitcode.com/G-YT/ANN/server/model/assess/request"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type ImageAssessService struct{}

// generateImageKey 生成唯一的纯数字ImageKey
func (imageAssessService *ImageAssessService) generateImageKey() string {
	// 生成17位纯数字的唯一标识
	// 使用时间戳(13位) + 随机数(4位)确保唯一性
	timestamp := time.Now().UnixMilli() // 13位时间戳

	// 生成4位随机数 (1000-9999)
	randomNum, _ := rand.Int(rand.Reader, big.NewInt(9000))
	randomPart := randomNum.Int64() + 1000

	return fmt.Sprintf("%d%04d", timestamp, randomPart)
}

// Image2Points 图像评估服务 - 调用第三方API进行图像分析
func (imageAssessService *ImageAssessService) Image2Points(req *request.ImageAssessRequest) (result string, err error) {
	// 自动生成唯一的纯数字ImageKey
	ImageKey := imageAssessService.generateImageKey()
	// 第三方API地址
	url := "https://jiepou.vesal.cn/vesal-jiepao-prod/evaluatemaster/open/v1/app/appraise/image2Points"

	// 构建请求体
	requestBody := map[string]interface{}{
		"appraiseType": req.AppraiseType,
		"imageType":    req.ImageType,
		"url":          req.URL,
		"imageKey":     ImageKey,
		"clearBack":    req.ClearBack,
	}

	// 将请求体转换为JSON
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		return "", fmt.Errorf("JSON序列化失败: %v", err)
	}

	// 创建HTTP客户端，设置超时时间
	client := &http.Client{
		Timeout: 300 * time.Second,
	}

	// 创建HTTP请求
	httpReq, err := http.NewRequest("POST", url, bytes.NewReader(jsonData))
	if err != nil {
		return "", fmt.Errorf("创建HTTP请求失败: %v", err)
	}

	// 设置请求头
	httpReq.Header.Set("business", "evaluatemaster")
	httpReq.Header.Set("apiKey", "EL1vinjyB84JGTJ733c3yM7CyCTdxRrKchhObxIALImorHeHew")
	httpReq.Header.Set("Content-Type", "application/json")

	// 发送HTTP请求
	resp, err := client.Do(httpReq)
	if err != nil {
		return "", fmt.Errorf("HTTP请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("读取响应体失败: %v", err)
	}

	// 检查HTTP状态码
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP请求失败，状态码: %d, 响应: %s", resp.StatusCode, string(body))
	}

	// 解析响应JSON

	var apiResponse map[string]interface{}
	if err := json.Unmarshal(body, &apiResponse); err != nil {

		//// 如果JSON解析失败，返回原始响应
		//resultJson := &response.ImageAssessResponse{
		//	Code:    resp.StatusCode,
		//	Message: "响应解析失败",
		//	Data:    string(body),
		//	Success: false,
		//}
		return result, nil
	}

	// 提取并处理data字段，只保留imgUrl和dicPoint
	var filteredData map[string]interface{}
	if data, exists := apiResponse["data"]; exists {
		if dataStr, ok := data.(string); ok {
			// 如果data是字符串，先解析
			var parsedData map[string]interface{}
			if err := json.Unmarshal([]byte(dataStr), &parsedData); err == nil {
				// 只保留imgUrl和dicPoint字段
				filteredData = make(map[string]interface{})
				if imgUrl, exists := parsedData["imgUrl"]; exists {
					filteredData["imgUrl"] = imgUrl
				}
				if dicPoint, exists := parsedData["dicPoint"]; exists {
					filteredData["dicPoint"] = dicPoint
				}
			}
		} else if dataMap, ok := data.(map[string]interface{}); ok {
			// 创建过滤后的数据结构，只保留imgUrl和dicPoint，确保顺序
			filteredData = map[string]interface{}{
				"imgUrl":   dataMap["imgUrl"],
				"dicPoint": dataMap["dicPoint"],
			}
		}
	}

	// 手动构建JSON字符串以确保字段顺序
	if filteredData != nil {
		var jsonBuilder strings.Builder
		jsonBuilder.WriteString("{")

		// 先添加imgUrl
		if imgUrl, exists := filteredData["imgUrl"]; exists {
			imgUrlBytes, _ := json.Marshal(imgUrl)
			jsonBuilder.WriteString("\"imgUrl\":")
			jsonBuilder.Write(imgUrlBytes)
		}

		// 再添加dicPoint，按数字顺序排列key
		if dicPoint, exists := filteredData["dicPoint"]; exists {
			if jsonBuilder.Len() > 1 { // 如果已经有内容，添加逗号
				jsonBuilder.WriteString(",")
			}

			// 处理dicPoint的排序
			if dicPointMap, ok := dicPoint.(map[string]interface{}); ok {
				// 获取所有key并按数字顺序排序
				keys := make([]string, 0, len(dicPointMap))
				for k := range dicPointMap {
					keys = append(keys, k)
				}

				// 按数字大小排序
				sort.Slice(keys, func(i, j int) bool {
					num1, err1 := strconv.Atoi(keys[i])
					num2, err2 := strconv.Atoi(keys[j])
					if err1 != nil || err2 != nil {
						return keys[i] < keys[j] // 如果转换失败，按字符串排序
					}
					return num1 < num2
				})

				// 手动构建dicPoint的JSON
				jsonBuilder.WriteString("\"dicPoint\":{")
				for idx, key := range keys {
					if idx > 0 {
						jsonBuilder.WriteString(",")
					}
					// 将坐标值转换为字符串格式，保持与appraiseImages一致
					if coordValue, ok := dicPointMap[key]; ok {
						// 先序列化坐标值，然后转换为字符串格式
						coordBytes, _ := json.Marshal(coordValue)
						coordStr := string(coordBytes)
						// 将坐标包装为字符串，替换[]为()
						coordStr = strings.ReplaceAll(coordStr, "[", "(")
						coordStr = strings.ReplaceAll(coordStr, "]", ")")
						// 构建最终的key-value对，坐标值作为字符串
						jsonBuilder.WriteString("\"" + key + "\":\"" + coordStr + "\"")
					}
				}
				jsonBuilder.WriteString("}")
			} else {
				// 如果不是map类型，直接序列化
				dicPointBytes, _ := json.Marshal(dicPoint)
				jsonBuilder.WriteString("\"dicPoint\":")
				jsonBuilder.Write(dicPointBytes)
			}
		}

		jsonBuilder.WriteString("}")
		dataStr := jsonBuilder.String()

		// 替换所有的[]为()
		result = strings.ReplaceAll(dataStr, "[", "(")
		result = strings.ReplaceAll(result, "]", ")")
	}

	return result, nil
}

// SubmitAssess 提交评估
func (imageAssessService *ImageAssessService) SubmitAssess(req *request.SaveAssessResultRequest) (result interface{}, err error) {
	// 开始数据库事务
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 第三方API地址
		url := "https://jiepou.vesal.cn/vesal-jiepao-prod/evaluatemaster/open/v1/app/appraise/save"
		// 构建请求体
		requestBody := map[string]interface{}{
			"appraiseImages":          req.AppraiseImages,
			"appraiseTypeId":          req.AppraiseTypeId,
			"appraiseTypeCode":        req.AppraiseTypeCode,
			"clearBackgroundStatus":   req.ClearBackgroundStatus,
			"reportPrivacyFaceStatus": req.ReportPrivacyFaceStatus,
			"version":                 req.Version,
			"platform":                req.Platform,
			"mbName":                  req.MbName,
			"mbTell":                  req.MbTell,
			"mbSex":                   req.MbSex,
			"birthday":                req.Birthday,
			"kg":                      req.Kg,
			"cm":                      req.Cm,
			"waistline":               req.Waistline,
			"hipline":                 req.Hipline,
		}
		// 将请求体转换为JSON
		jsonData, MarshalErr := json.Marshal(requestBody)
		if MarshalErr != nil {
			return errors.New("JSON序列化失败")
		}

		// 创建HTTP客户端，设置超时时间
		client := &http.Client{
			Timeout: 600 * time.Second, // 保存操作可能需要更长时间
		}

		// 创建HTTP请求
		httpReq, NewRequestErr := http.NewRequest("POST", url, bytes.NewReader(jsonData))
		if NewRequestErr != nil {
			return errors.New("创建HTTP请求失败")
		}

		// 设置请求头
		httpReq.Header.Set("business", "evaluatemaster")
		httpReq.Header.Set("apiKey", "EL1vinjyB84JGTJ733c3yM7CyCTdxRrKchhObxIALImorHeHew")
		httpReq.Header.Set("Content-Type", "application/json")

		// 发送HTTP请求
		resp, clientErr := client.Do(httpReq)
		if clientErr != nil {
			return errors.New("HTTP请求失败")
		}
		defer resp.Body.Close()

		// 读取响应体
		body, ReadAllErr := io.ReadAll(resp.Body)
		if ReadAllErr != nil {
			return errors.New("读取响应体失败")
		}

		// 检查HTTP状态码
		if resp.StatusCode != http.StatusOK {
			return errors.New("HTTP请求失败,通过状态码检查")
		}

		// 解析响应JSON
		var apiResponse map[string]interface{}
		if UnmarshalErr := json.Unmarshal(body, &apiResponse); UnmarshalErr != nil {
			return errors.New("响应JSON解析失败")
		}

		// 检查API响应状态
		if code, exists := apiResponse["code"]; exists {
			if codeInt, ok := code.(float64); ok {
				if codeInt != 0 {
					msg := "未知错误"
					if message, exists := apiResponse["msg"]; exists {
						if msgStr, ok := message.(string); ok {
							msg = msgStr
						}
					}
					return errors.New("API调用失败:" + msg)
				}
			}
		}

		// 同步保存评估记录到数据库
		// 查找或创建客户记录
		var customer assess.Customer
		if customerErr := tx.Where("phone = ?", req.MbTell).First(&customer).Error; customerErr != nil {
			return errors.New("客户档案不存在")
		}

		// 处理details字段 - 完整存储第三方接口返回的data.details全部内容
		var details string
		var age uint
		if data, exists := apiResponse["data"]; exists {
			if dataMap, ok := data.(map[string]interface{}); ok {
				// 提取details字段 - 完整存储包括所有嵌套结构和元数据
				if detailsData, detailsExists := dataMap["details"]; detailsExists {
					// 直接将details数据序列化为JSON字符串，保持原始格式
					if detailsBytes, err := json.Marshal(detailsData); err == nil {
						details = string(detailsBytes)
					}
				}

				// 提取age字段 - 直接存储第三方接口返回的data.age值
				if ageData, ageExists := dataMap["age"]; ageExists {
					if ageFloat, ok := ageData.(float64); ok {
						age = uint(ageFloat)
					} else if ageInt, ok := ageData.(int); ok {
						age = uint(ageInt)
					}
				}
			}
		}

		// 创建评估记录 - 直接存储原始数据，严格禁止JSON转义、格式化或编码转换
		assessRecord := assess.AssessRecord{
			CID:                     customer.ID,
			AppraiseImages:          req.AppraiseImages, // 直接存储原始JSON字符串，禁止转义处理
			AppraiseTypeId:          req.AppraiseTypeId,
			AppraiseTypeCode:        req.AppraiseTypeCode,
			ClearBackgroundStatus:   req.ClearBackgroundStatus,
			ReportPrivacyFaceStatus: req.ReportPrivacyFaceStatus,
			Version:                 req.Version,
			Platform:                req.Platform,
			MbName:                  req.MbName,
			MbTell:                  req.MbTell,
			MbSex:                   req.MbSex,
			Birthday:                req.Birthday,
			Kg:                      req.Kg,
			Cm:                      req.Cm,
			Waistline:               req.Waistline,
			Hipline:                 req.Hipline,
			Details:                 details, // 完整存储第三方接口返回的data.details，包括所有嵌套结构
			Age:                     age,     // 直接存储第三方接口返回的data.age值
		}

		if details != "" {
			// 保存评估记录
			if CreateErr := tx.Create(&assessRecord).Error; CreateErr != nil {
				return errors.New("保存评估记录失败")
			}
		}

		// 处理API响应数据并替换id为数据库记录ID
		processedData := imageAssessService.processResponseData(apiResponse["data"])

		// 将返回数据中的id替换为保存的评估记录ID
		if dataMap, ok := processedData.(map[string]interface{}); ok {
			dataMap["id"] = assessRecord.ID
			result = dataMap
		}
		return nil
	})
	return
}

// processJSONField 处理JSON字段，类似Qsttpg方法的处理逻辑
// 将存储的JSON字符串转换为标准化的JSON对象，保留原始数据结构
// deepParseJSON 深度解析JSON字符串，处理多层嵌套的JSON字符串情况
// 支持递归解析和完整的类型检查，确保返回标准JavaScript对象
func (imageAssessService *ImageAssessService) deepParseJSON(data interface{}, depth int) (interface{}, error) {
	// 防止无限递归，设置最大深度限制
	const maxDepth = 10
	if depth > maxDepth {
		return data, fmt.Errorf("JSON parsing depth exceeded maximum limit: %d", maxDepth)
	}

	switch v := data.(type) {
	case string:
		// 尝试解析字符串为JSON
		if strings.TrimSpace(v) == "" {
			return v, nil
		}

		// 检查是否为JSON格式的字符串
		if (strings.HasPrefix(v, "{") && strings.HasSuffix(v, "}")) ||
			(strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]")) {
			var parsed interface{}
			if err := json.Unmarshal([]byte(v), &parsed); err != nil {
				// 如果解析失败，返回原始字符串
				return v, nil
			}
			// 递归解析嵌套的JSON
			return imageAssessService.deepParseJSON(parsed, depth+1)
		}
		return v, nil

	case map[string]interface{}:
		// 递归处理对象中的每个值
		result := make(map[string]interface{})
		for key, value := range v {
			parsed, err := imageAssessService.deepParseJSON(value, depth+1)
			if err != nil {
				return nil, fmt.Errorf("error parsing key '%s': %w", key, err)
			}
			result[key] = parsed
		}
		return result, nil

	case []interface{}:
		// 递归处理数组中的每个元素
		result := make([]interface{}, len(v))
		for i, value := range v {
			parsed, err := imageAssessService.deepParseJSON(value, depth+1)
			if err != nil {
				return nil, fmt.Errorf("error parsing array index %d: %w", i, err)
			}
			result[i] = parsed
		}
		return result, nil

	default:
		// 其他类型直接返回
		return v, nil
	}
}

// processJSONField 处理JSON字符串字段，支持深度解析和转义字符处理
func (imageAssessService *ImageAssessService) processJSONField(jsonStr string) interface{} {
	if jsonStr == "" {
		return nil
	}

	// 记录调试信息
	if global.GVA_LOG != nil {
		global.GVA_LOG.Debug("开始处理JSON字段", zap.String("原始数据", jsonStr))
	}

	// 数据预处理：清理可能的转义字符和格式问题
	cleanedStr := imageAssessService.cleanJSONString(jsonStr)

	if global.GVA_LOG != nil {
		global.GVA_LOG.Debug("清理后的JSON", zap.String("清理后数据", cleanedStr))
	}

	// 第一次JSON解析
	var firstParse interface{}
	if err := json.Unmarshal([]byte(cleanedStr), &firstParse); err != nil {
		if global.GVA_LOG != nil {
			global.GVA_LOG.Debug("初始JSON解析失败", zap.Error(err))
		}
		return jsonStr // 优雅降级：返回原始字符串
	}

	// 深度解析处理多层嵌套JSON
	result, err := imageAssessService.deepParseJSON(firstParse, 0)
	if err != nil {
		if global.GVA_LOG != nil {
			global.GVA_LOG.Debug("深度解析失败", zap.Error(err))
		}
		return firstParse // 优雅降级：返回第一次解析结果
	}

	// 数据验证：确保解析后的数据结构完整
	if err := imageAssessService.validateParsedData(result, jsonStr); err != nil {
		if global.GVA_LOG != nil {
			global.GVA_LOG.Warn("数据验证警告", zap.Error(err))
		}
	}

	return result
}

// cleanJSONString 清理JSON字符串中的转义字符和格式问题
func (imageAssessService *ImageAssessService) cleanJSONString(jsonStr string) string {
	// 移除字符串开头和结尾的多余引号和空格
	cleaned := strings.TrimSpace(jsonStr)

	// 处理被双重引号包装的JSON字符串
	if strings.HasPrefix(cleaned, "\"") && strings.HasSuffix(cleaned, "\"") {
		// 移除外层引号
		cleaned = cleaned[1 : len(cleaned)-1]
	}

	// 处理转义的引号 - 这是关键步骤
	cleaned = strings.ReplaceAll(cleaned, "\\\"", "\"")

	// 处理转义的反斜杠
	cleaned = strings.ReplaceAll(cleaned, "\\\\", "\\")

	// 处理其他常见的转义字符
	cleaned = strings.ReplaceAll(cleaned, "\\n", "\n")
	cleaned = strings.ReplaceAll(cleaned, "\\t", "\t")
	cleaned = strings.ReplaceAll(cleaned, "\\r", "\r")

	return cleaned
}

// validateParsedData 验证解析后的数据完整性
func (imageAssessService *ImageAssessService) validateParsedData(parsed interface{}, original string) error {
	// 基本类型检查
	if parsed == nil && original != "" && original != "null" {
		return fmt.Errorf("parsed result is nil but original data is not empty")
	}

	// 检查是否为有效的对象或数组
	switch v := parsed.(type) {
	case map[string]interface{}:
		if len(v) == 0 && len(original) > 10 { // 原始数据较长但解析结果为空对象
			return fmt.Errorf("parsed object is empty but original data suggests non-empty content")
		}
	case []interface{}:
		if len(v) == 0 && len(original) > 10 { // 原始数据较长但解析结果为空数组
			return fmt.Errorf("parsed array is empty but original data suggests non-empty content")
		}
	case string:
		// 如果解析结果仍然是字符串，检查是否应该是对象或数组
		trimmed := strings.TrimSpace(v)
		if (strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[")) && len(trimmed) > 2 {
			return fmt.Errorf("parsed result is still a JSON string, may need further parsing")
		}
	}

	return nil
}

// GetAssessRecordList 获取评估记录列表 - 筛选条件(评估类型,手机号,日期)
func (imageAssessService *ImageAssessService) GetAssessRecordList(info request.AssessRecordSearch, hmID uint) (list []map[string]interface{}, total int64, err error) {
	// 首先获取该健管师的所有客户ID
	var customerIDs []uint
	err = global.GVA_DB.Model(&assess.Customer{}).Where("hmID = ?", hmID).Pluck("id", &customerIDs).Error
	if err != nil {
		return nil, 0, err
	}
	// 如果该健管师没有客户，直接返回空结果
	if len(customerIDs) == 0 {
		return []map[string]interface{}{}, 0, nil
	}

	// 构建查询条件 - 只查询该健管师客户的评估记录
	db := global.GVA_DB.Model(&assess.AssessRecord{}).Where("cid IN (?)", customerIDs)

	// 添加其他查询条件
	if info.CustomerID != 0 {
		db = db.Where("cid = ?", info.CustomerID)
	}
	if info.MbName != "" {
		db = db.Where("mb_name LIKE ?", "%"+info.MbName+"%")
	}
	if info.MbTell != "" {
		db = db.Where("mb_tell LIKE ?", "%"+info.MbTell+"%")
	}
	if info.AppraiseTypeId != 0 {
		db = db.Where("appraise_type_id = ?", info.AppraiseTypeId)
	}
	if info.AppraiseTypeCode != "" {
		db = db.Where("appraise_type_code = ?", info.AppraiseTypeCode)
	}
	if info.StartDate != "" {
		db = db.Where("DATE(created_at) >= ?", info.StartDate)
	}
	if info.EndDate != "" {
		db = db.Where("DATE(created_at) <= ?", info.EndDate)
	}

	// 获取总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 获取所有记录（不分页，因为需要按日期分组）
	var assessRecords []assess.AssessRecord
	if info.OrderBy != "" {
		err = db.Preload("Customer").Order(info.OrderBy).Find(&assessRecords).Error
		if err != nil {
			return nil, 0, err
		}
	} else {
		err = db.Preload("Customer").Order("created_at DESC").Find(&assessRecords).Error
		if err != nil {
			return nil, 0, err
		}
	}
	// 处理每条记录，转换为标准化的map格式并处理JSON字段
	list = make([]map[string]interface{}, 0, len(assessRecords))
	for _, record := range assessRecords {
		recordMap := map[string]interface{}{
			"id":                      record.ID,
			"customerId":              record.CID,
			"customer":                record.Customer,
			"appraiseImages":          imageAssessService.processJSONField(record.AppraiseImages), // 转换为标准化JSON对象
			"appraiseTypeId":          record.AppraiseTypeId,
			"appraiseTypeCode":        record.AppraiseTypeCode,
			"clearBackgroundStatus":   record.ClearBackgroundStatus,
			"reportPrivacyFaceStatus": record.ReportPrivacyFaceStatus,
			"version":                 record.Version,
			"platform":                record.Platform,
			"mbName":                  record.MbName,
			"mbTell":                  record.MbTell,
			"mbSex":                   record.MbSex,
			"birthday":                record.Birthday,
			"kg":                      record.Kg,
			"cm":                      record.Cm,
			"waistline":               record.Waistline,
			"hipline":                 record.Hipline,
			"details":                 imageAssessService.processJSONField(record.Details), // 转换为标准化JSON对象，保留完整数据结构
			"age":                     record.Age,                                          // 返回原始age值
			"createdAt":               record.CreatedAt,
			"updatedAt":               record.UpdatedAt,
		}
		list = append(list, recordMap)
	}

	return
}

// GetAssessRecordListByDate 获取评估记录列表 - 按日期分组，通过健管师ID过滤
func (imageAssessService *ImageAssessService) GetAssessRecordListByDate(info request.AssessRecordSearch, hmID uint) (list interface{}, total int64, err error) {
	// 首先获取该健管师的所有客户ID
	var customerIDs []uint
	err = global.GVA_DB.Model(&assess.Customer{}).Where("hmID = ?", hmID).Pluck("id", &customerIDs).Error
	if err != nil {
		return nil, 0, err
	}

	// 如果该健管师没有客户，直接返回空结果
	if len(customerIDs) == 0 {
		return []map[string]interface{}{}, 0, nil
	}

	// 构建查询条件 - 只查询该健管师客户的评估记录
	db := global.GVA_DB.Model(&assess.AssessRecord{}).Where("cid IN (?)", customerIDs)

	// 添加其他查询条件
	if info.CustomerID != 0 {
		db = db.Where("cid = ?", info.CustomerID)
	}
	if info.MbName != "" {
		db = db.Where("mb_name LIKE ?", "%"+info.MbName+"%")
	}
	if info.MbTell != "" {
		db = db.Where("mb_tell LIKE ?", "%"+info.MbTell+"%")
	}
	if info.AppraiseTypeId != 0 {
		db = db.Where("appraise_type_id = ?", info.AppraiseTypeId)
	}
	if info.AppraiseTypeCode != "" {
		db = db.Where("appraise_type_code = ?", info.AppraiseTypeCode)
	}
	if info.StartDate != "" {
		db = db.Where("DATE(created_at) >= ?", info.StartDate)
	}
	if info.EndDate != "" {
		db = db.Where("DATE(created_at) <= ?", info.EndDate)
	}

	// 获取总数
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 获取所有记录（不分页，因为需要按日期分组）
	var assessRecords []assess.AssessRecord
	err = db.Preload("Customer").Order("created_at DESC").Find(&assessRecords).Error
	if err != nil {
		return nil, 0, err
	}

	// 按创建日期分组
	dateGroups := make(map[string][]map[string]interface{})

	for _, record := range assessRecords {
		// 获取创建日期（格式：2025-01-20）
		dateKey := record.CreatedAt.Format("2006-01-02")

		// 构建记录数据
		recordMap := map[string]interface{}{
			"id":                      record.ID,
			"customerId":              record.CID,
			"customerName":            record.Customer.Name,
			"customerPhone":           record.Customer.Phone,
			"appraiseImages":          imageAssessService.processJSONField(record.AppraiseImages), // 转换为标准化JSON对象
			"appraiseTypeId":          record.AppraiseTypeId,
			"appraiseTypeCode":        record.AppraiseTypeCode,
			"clearBackgroundStatus":   record.ClearBackgroundStatus,
			"reportPrivacyFaceStatus": record.ReportPrivacyFaceStatus,
			"version":                 record.Version,
			"platform":                record.Platform,
			"mbName":                  record.MbName,
			"mbTell":                  record.MbTell,
			"mbSex":                   record.MbSex,
			"birthday":                record.Birthday,
			"kg":                      record.Kg,
			"cm":                      record.Cm,
			"waistline":               record.Waistline,
			"hipline":                 record.Hipline,
			"details":                 imageAssessService.processJSONField(record.Details), // 转换为标准化JSON对象，保留完整数据结构
			"age":                     record.Age,                                          // 返回原始age值
			"createdAt":               record.CreatedAt,
			"updatedAt":               record.UpdatedAt,
		}

		// 将记录添加到对应日期的分组中
		dateGroups[dateKey] = append(dateGroups[dateKey], recordMap)
	}

	// 构建最终返回结果 - 按日期分组的数组
	var result []map[string]interface{}

	// 获取所有日期并排序（最新日期在前）
	var dates []string
	for date := range dateGroups {
		dates = append(dates, date)
	}
	sort.Slice(dates, func(i, j int) bool {
		return dates[i] > dates[j] // 降序排列，最新日期在前
	})

	// 按排序后的日期构建结果
	for _, date := range dates {
		records := dateGroups[date]
		dateGroup := map[string]interface{}{
			"date":    date,
			"records": records,
		}
		result = append(result, dateGroup)
	}

	return result, total, nil
}

// GetAssessRecord 获取单个评估记录详情
func (imageAssessService *ImageAssessService) GetAssessRecord(id uint) (record map[string]interface{}, err error) {
	var assessRecord assess.AssessRecord
	err = global.GVA_DB.Preload("Customer").Where("id = ?", id).First(&assessRecord).Error
	if err != nil {
		return nil, err
	}

	// 构建返回数据 - 返回标准化JSON对象
	record = map[string]interface{}{
		"id":                      assessRecord.ID,
		"customerId":              assessRecord.CID,
		"customer":                assessRecord.Customer,
		"appraiseImages":          imageAssessService.processJSONField(assessRecord.AppraiseImages), // 转换为标准化JSON对象
		"appraiseTypeId":          assessRecord.AppraiseTypeId,
		"appraiseTypeCode":        assessRecord.AppraiseTypeCode,
		"clearBackgroundStatus":   assessRecord.ClearBackgroundStatus,
		"reportPrivacyFaceStatus": assessRecord.ReportPrivacyFaceStatus,
		"version":                 assessRecord.Version,
		"platform":                assessRecord.Platform,
		"mbName":                  assessRecord.MbName,
		"mbTell":                  assessRecord.MbTell,
		"mbSex":                   assessRecord.MbSex,
		"birthday":                assessRecord.Birthday,
		"kg":                      assessRecord.Kg,
		"cm":                      assessRecord.Cm,
		"waistline":               assessRecord.Waistline,
		"hipline":                 assessRecord.Hipline,
		"details":                 imageAssessService.processJSONField(assessRecord.Details), // 转换为标准化JSON对象，保留完整数据结构
		"age":                     assessRecord.Age,                                          // 返回原始age值
		"createdAt":               assessRecord.CreatedAt,
		"updatedAt":               assessRecord.UpdatedAt,
	}

	return record, nil
}

// processResponseData 处理响应数据，去除指定字段的外层双引号和转义符
func (imageAssessService *ImageAssessService) processResponseData(data interface{}) interface{} {
	switch v := data.(type) {
	case map[string]interface{}:
		result := make(map[string]interface{})
		for key, value := range v {
			// 使用新的专门处理方法处理appraiseImages和details字段
			if key == "details" || key == "appraiseImages" {
				result[key] = imageAssessService.processSpecialFields(key, value)
			} else {
				// 其他字段递归处理
				result[key] = imageAssessService.processResponseData(value)
			}
		}
		return result
	case []interface{}:
		result := make([]interface{}, len(v))
		for i, item := range v {
			result[i] = imageAssessService.processResponseData(item)
		}
		return result
	case string:
		// 对于普通字符串，只进行基本的反转义处理
		return imageAssessService.unescapeJSONString(v)
	default:
		return v
	}
}

// processSpecialFields 专门处理appraiseImages和details字段的反转义和标准化
func (imageAssessService *ImageAssessService) processSpecialFields(fieldName string, value interface{}) interface{} {
	// 只处理appraiseImages和details字段
	if fieldName != "appraiseImages" && fieldName != "details" {
		return value
	}

	strValue, ok := value.(string)
	if !ok {
		// 如果不是字符串类型，直接返回原值
		return value
	}

	// 去除前后空白字符
	trimmed := strings.TrimSpace(strValue)
	if trimmed == "" {
		return trimmed
	}

	// 处理被双引号包裹的JSON字符串
	processed := imageAssessService.removeOuterQuotesAndUnescapeJSON(trimmed)

	return processed
}

// removeOuterQuotesAndUnescapeJSON 去除最外层双引号并反转义JSON字符串
func (imageAssessService *ImageAssessService) removeOuterQuotesAndUnescapeJSON(str string) interface{} {
	// 检查是否被双引号包裹
	if len(str) >= 2 && str[0] == '"' && str[len(str)-1] == '"' {
		// 去除最外层双引号
		unquoted := str[1 : len(str)-1]

		// 反转义JSON字符串
		unescaped := imageAssessService.unescapeJSONString(unquoted)

		// 尝试解析为标准JSON对象
		var parsed interface{}
		if err := json.Unmarshal([]byte(unescaped), &parsed); err == nil {
			// 成功解析为JSON对象，返回解析后的标准化数据
			return parsed
		}

		// 如果无法解析为JSON，返回反转义后的字符串
		return unescaped
	}

	// 如果没有被双引号包裹，尝试直接解析
	var parsed interface{}
	if err := json.Unmarshal([]byte(str), &parsed); err == nil {
		return parsed
	}

	// 如果都无法解析，返回原字符串
	return str
}

// unescapeJSONString 反转义JSON字符串中的所有转义字符
func (imageAssessService *ImageAssessService) unescapeJSONString(str string) string {
	// 按照JSON标准反转义规则处理
	result := str

	// 处理转义的双引号
	result = strings.ReplaceAll(result, "\\\"", "\"")

	// 处理转义的反斜杠（必须在其他转义处理之后）
	result = strings.ReplaceAll(result, "\\\\", "\\")

	// 处理转义的正斜杠
	result = strings.ReplaceAll(result, "\\/", "/")

	// 处理转义的控制字符
	result = strings.ReplaceAll(result, "\\n", "\n")
	result = strings.ReplaceAll(result, "\\r", "\r")
	result = strings.ReplaceAll(result, "\\t", "\t")
	result = strings.ReplaceAll(result, "\\b", "\b")
	result = strings.ReplaceAll(result, "\\f", "\f")

	return result
}

// removeOuterQuotesAndEscapes 去除字符串外层双引号并移除转义符（保持向后兼容）
func (imageAssessService *ImageAssessService) removeOuterQuotesAndEscapes(str string) interface{} {
	return imageAssessService.removeOuterQuotesAndUnescapeJSON(str)
}

// removeEscapeCharacters 移除字符串中的反斜杠转义符（保持向后兼容）
func (imageAssessService *ImageAssessService) removeEscapeCharacters(str string) string {
	return imageAssessService.unescapeJSONString(str)
}
